<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User_token extends CI_Model{
	
	public $table; // table name

	function __construct(){
		parent::__construct();
		$this->load->database();
		$this->table = 'user_token';
	}

	public function getByTid($tid){
		return $this->db->get_where($this->table,array('tid'=>$tid))->row_array();

	}
	/**
	 * [upload description]
	 * @param  [type] $where [description]
	 * @param  [type] $data  [description]
	 * @return [type]        [description]
	 */
	public function update($where,$data){
		$this->db->where($where);
		$this->db->update($this->table,$data);
		return $this->db->affected_rows();
	}
	/**
	 * [checkToken ]
	 * @param  [string] $token [description]
	 * @return [bool]        [is the token correct or not]
	 */
	public function checkToken($token){
		if(!$token) return false;

		$this->db->select('token,tid');
		$this->db->where('token',$token);

		$rs = $this->db->get($this->table)->result_array();
		// var_dump($this->db->last_query());
		// die;
		return !empty($rs) ? $rs[0] : false;
	}

	/**
	 * [saveUser description]
	 * @param  [type] $info [description]
	 * @return [type]       [description]
	 */
	public function saveUser($info){
		if(is_string($info)) $info = json_decode($info);
		if(is_array($info))  $info = json_decode(json_encode($info));

		$this->db->select('token');
		$this->db->where(array('tid'=>$info->tid,'token'=>$info->token));

		$rs = $this->db->get($this->table)->row();

		// var_dump($this->db->last_query());
		// var_dump($rs);
		// die;
		// create local user when there is not the user info
		if(!$rs){
			$this->db->insert($this->table,$info);
		}

	}

	

}